package com.mvc4g.example.mockup.client.action;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.mvc4g.client.ActionInterface;
import com.mvc4g.client.Controller;
import com.mvc4g.example.mockup.client.Constants;
import com.mvc4g.example.mockup.client.MockUpService;
import com.mvc4g.example.mockup.client.MockUpServiceAsync;
import com.mvc4g.example.mockup.client.Session;
import com.mvc4g.example.mockup.client.bean.LoginBean;
import com.mvc4g.example.mockup.client.view.templates.LoggedTemplate;
import com.mvc4g.example.mockup.client.view.templates.RootTemplate;
import com.mvc4g.example.mockup.client.view.views.AbstractView;

public class LoginAction implements ActionInterface, Constants {
	
	private static MockUpServiceAsync services = MockUpService.Util.getInstance();

	@Override
	public void execute(final Controller controller, Object form) {
		
		final LoginBean loginBean = (LoginBean) form;
		
		services.login(loginBean, new AsyncCallback<Void>(){

			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onSuccess(Void result) {
				
				Session.setAttribute(LOGIN, loginBean.getLogin());
				
				LoggedTemplate loggedTemplate = (LoggedTemplate) controller.getView(LOGGED_TEMPLATE);
				
				RootTemplate rootView = (RootTemplate) controller.getView(ROOT_TEMPLATE);				
				rootView.changePage(loggedTemplate, null);
				
				AbstractView welcomeView = (AbstractView) controller.getView(WELCOME_VIEW);				
				loggedTemplate.changePage(welcomeView, GO_TO_WELCOME_PAGE);
														
			}
			
		});
	}

}
